use std::str::FromStr;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    // TODO: 这里写逻辑
    let num = decode(num_str);
    encode(num, to_base as i32)
}

fn encode(mut num: i32, base: i32) -> String {
    let code: Vec<_> = "0123456789abcdef".chars().collect();
    let mut res = String::new();
    let flag = match num < 0 {
        true => {
            num = -num;
            -1
        }
        false => 1,
    };
    loop {
        if num == 0 {
            break;
        }
        let c = code[(num % base) as usize];
        res.insert(0, c);
        num /= base;
        if num == 0 {
            break;
        }
    }
    if flag == -1 {
        res.insert(0, '-');
    }
    res
}

fn decode(num: &str) -> i32 {
    let nums: Vec<_> = num.split("(").collect();
    let num = nums[0];
    let base = nums[1].split(")").collect::<Vec<_>>()[0];
    let base = i32::from_str(base).unwrap();
    let mut flag = 1;
    let mut res = 0;

    for c in num.chars() {
        res = res * base;
        match c {
            '-' => flag = -1,
            'a' => res += 10,
            'b' => res += 11,
            'c' => res += 12,
            'd' => res += 13,
            'e' => res += 14,
            'f' => res += 15,
            _ => res += c as i32 - '0' as i32,
        }
    }
    res *= flag;

    res
}